#include <iostream>
#include <string>

#include <unistd.h>

#include "search.hpp"
#include "cpp-httplib/httplib.h"
#include "log.hpp"

Log server_log;

const std::string raw_file = "./data/raw_html/raw.bin";
const std::string root_path = "./wwwroot";

int main()
{
#ifndef __TEST__DEBUG__1
    server_log.change_method(Class);
    daemon(1, 0);
    server_log(Debug, "daemon over, http_server pid: %d", getpid());
#endif

    qyc::search_html search;
    search.init_search(raw_file);

    httplib::Server svr;
    // 设置网页根目录
    svr.set_base_dir(root_path.c_str());

    // 配置网页get操作, /hi访问路径 lambda表达式参数 request请求,resp回应
    svr.Get("/s", [&search](const httplib::Request& req, httplib::Response& resp)
    {
        // 判断是否有参
        if (!req.has_param("word"))
        {
            resp.set_content("必须有搜索关键字", "text/plain; charset=utf-8");
            return;
        }
        // 获得用户输入的参数
        std::string word = req.get_param_value("word");
        // std::cout << "用户搜索: " << word << std::endl;
        server_log(Info, "用户搜索: %s", word.c_str());

        std::string json_string;
        search.search(word, json_string);
        // std::cout << "本次搜索完成" << std::endl;
        server_log(Info, "本次搜索完成");
        // 设置resp的回调函数显示信息   json_string返回信息 application/json以json的方式让浏览器显示
        resp.set_content(json_string.c_str(), "application/json");
    });
    svr.listen("0.0.0.0", 8080);
    return 0;
}